const connection = require("./connection");
const config = require("./config");

function query(sql) {
  return new Promise((on, off) => {
    connection()
      .then((t) => {
        t.query(sql, function (error, results) {
          let data = JSON.parse(JSON.stringify(results));
          t.end();
          if (error) off(error);
          else on(data);
        });
      })
      .catch(off);
  });
}

module.exports = {
  table: () => {
    return new Promise((on, off) => {
      query(`SELECT
TABLE_NAME as \`name\`,
TABLE_COMMENT as \`comment\`
FROM TABLES
WHERE TABLE_SCHEMA = '${config.schema}';`)
        .then(on)
        .catch(off);
    });
  },
  column: (table_name) => {
    return new Promise((on, off) => {
      query(`select
c.COLUMN_NAME as \`name\`,
c.COLUMN_COMMENT as \`comment\`,
c.IS_NULLABLE as \`nullable\`,
c.DATA_TYPE as \`type\`,
c.CHARACTER_MAXIMUM_LENGTH as \`max_length\`,
c.NUMERIC_PRECISION as \`precision\`,
c.NUMERIC_SCALE as \`scale\`,
k.COLUMN_NAME is not null as \`paimary\`
from information_schema.COLUMNS c
left JOIN
(select * from information_schema.key_column_usage where CONSTRAINT_NAME = 'PRIMARY') k
on c.TABLE_SCHEMA = k.TABLE_SCHEMA and c.TABLE_NAME = k.TABLE_NAME and c.COLUMN_NAME = k.COLUMN_NAME
where c.table_name = '${table_name}';`)
        .then(on)
        .catch(off);
    });
  },
};
